<template>
  <div class="login">
    <div class="bg">
      <div class="login-wrap">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate">
          <FormItem label="用户名" prop="name">
            <Input v-model="formValidate.name" placeholder="Enter your name"></Input>
          </FormItem>
          <FormItem label="密码" prop="password">
            <Input v-model="formValidate.password" type="password" placeholder="Enter your password"></Input>
          </FormItem>
          <FormItem style="text-align: center">
            <Button type="primary" @click="handleSubmit('formValidate')">login</Button>
          </FormItem>
        </Form>
      </div>
    </div>
  </div>
</template>

<script>
  import {LOGIN_URL} from '../../config/urls'
  import {setLocalStorage} from '../../lib/util'
  import {mapActions} from 'vuex'

  export default {
    data () {
      return {
        formValidate: {
          name: '',
          password: ''
        },
        ruleValidate: {
          name: [
            {required: true, message: '用户名必填', trigger: 'blur'}
          ],
          password: [{required: true, message: '密码必填', trigger: 'blur'}]
        }
      }
    },
    methods: {
      ...mapActions({userLoginAction: 'userLoginAction'}),
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$http.post(LOGIN_URL.login, this.formValidate)
              .then(data => {
                setLocalStorage(data.data.token)
                return data.data.token
              })
              .then(token => {
                this.$http.get(LOGIN_URL.user, {
                  headers: {'Authorization': token}
                })
                  .then(data => {
                    this.userLoginAction(data.data.data)
                    this.$router.push('/home')
                  })
                  .catch(err => console.log(err))
              })
              .catch(err => {
                this.$Message.error(err.response.data.message)
              })
          } else {
            this.$Message.error('请输入完整')
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .login{
    height: 100%;
    width: 100%;
    background: url("/static/img/wallhaven-443187.jpg") no-repeat center;
    background-size: cover;
    .bg {
      width: 100%;
      height: 100%;
      background: rgba(0,0,0, .5);
      display: flex;
      justify-content: center;
      align-items: center;
      .login-wrap{
        width: 400px;
        padding: 20px;
        border-radius: 10px;
        background: #fff;
      }
    }
  }
</style>
